package com.kylin.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kylin.eduservice.client.VodClient;
import com.kylin.eduservice.entity.EduVideo;
import com.kylin.eduservice.mapper.EduVideoMapper;
import com.kylin.eduservice.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author kylin
 * @since 2020-07-15
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    VodClient client;

    //根据课程id删除小节,应该删除对应视频
    @Override
    public void removeVideoByCourseId(String courseId) {
        //1.删除阿里云视频
        //根据Id获取到所有小节对象
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        //只查video_source_id字段
        queryWrapper.select("video_source_id");
        //select video_source_id from edu_video where course_id = #{courseId)
        List<EduVideo> eduVideoList = baseMapper.selectList(queryWrapper);
        //删除多个视频
        //List<EduVideo>变成List<String>
        List<String> videoIds = new ArrayList<>();

        for (EduVideo eduVideo : eduVideoList) {
            String id = eduVideo.getVideoSourceId();
            System.out.println(id);
            //判断小节视频ID是否为空
            if (!StringUtils.isEmpty(id)){
                videoIds.add(id);
            }
        }
        for (String videoId : videoIds) {
            System.out.print(videoId+"-");
        }
        //判断集合是否为空，避免所有小节对象没有视频存在而调用删除
        if (videoIds.size()>0){
            //调用远程服务
            client.deleteBatch(videoIds);
        }

        //2.删除所有小节
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<EduVideo>();
        wrapper.eq("course_id", courseId);

        baseMapper.delete(wrapper);
    }
}
